package com.alan.server.util;


import com.alan.server.enums.ServiceErrorCodeEnum;
import com.alan.server.exception.ServiceException;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 *
 * @author Alan
 */
public class EmptyCheckUtil {

	/**
	 * 非空校验
	 * 
	 * @param bean
	 * @param arg
	 * @throws Exception
	 */
	public static void check(Object bean, String... arg) throws Exception {
		if (bean == null) {
            throw new ServiceException(ServiceErrorCodeEnum.INPUT_MUST_NOT_NULL.getCode(), "Object为空");
		}
		Class type = bean.getClass();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			Method readMethod = descriptor.getReadMethod();
			Object result = readMethod.invoke(bean, new Object[0]);
			for (String attribute : arg) {
				if (attribute.equals(propertyName) && (result == null || result == "")) {
                    throw new ServiceException(ServiceErrorCodeEnum.INPUT_MUST_NOT_NULL.getCode(), attribute
                            + "为空", attribute);
				}
			}
		}
	}

}
